<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/25 0025
 * Time: 上午 9:57
 */

namespace app\admin\controller\company;


use app\admin\model\BranchAgency;
use app\admin\model\City;
use app\common\controller\Backend;

class BranchAreaAgency extends Backend
{
    protected $model = null;
    protected $relationSearch = true;
    protected $multiFields = 'open_share,is_ok';

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = model('BranchOffice');

    }

    public function index()
    {
        if ($this->request->isAjax())
        {
            $this->request->filter(['strip_tags']);

            $data = $this->request->get('data');
            $data = json_decode($data,true);
            $city_id = $data['city_id'];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams(NULL);

            $total = $this->model
                ->with('agency')
                ->where(['status'=>1,'type'=>3,'city_id'=>$city_id])
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('agency')
                ->where(['status'=>1,'type'=>3,'city_id'=>$city_id])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $key=>$item)
            {
                //处理地区
                $city_id = $item['city_id'];
                $city_info = (new City())->field('province,city,cityID,name')->where(['cityID'=>$city_id])->find();
                $province_name = (new City())->whereIn('cityID',[$city_info['province'],$city_info['city']])->column('name');
                $province_name = implode('-',$province_name);
                $list[$key]['area'] = $province_name.'-'.$city_info['name'];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->assign('city_id',$this->request->get('city_id'));
        return $this->view->fetch();
    }

    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids)
        {
            if ($this->request->has('params'))
            {
                parse_str($this->request->post("params"), $values);
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values)
                {
                    //是否开通
                    if (key_exists('is_ok',$values)&& $values['is_ok']){
                        $count = (new BranchAgency())->where('user_id','in',$ids)->update($values);
                        if ($count)
                        {
                            $this->success();
                        }
                        else
                        {
                            $this->error(__('No rows were updated'));
                        }
                    }

                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds))
                    {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    $count = $this->model->where($this->model->getPk(), 'in', $ids)->update($values);
                    if ($count)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error(__('No rows were updated'));
                    }
                }
                else
                {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                /*
                 * 已经弃用,如果为了兼容老版可取消注释
                  foreach ($params as $k => &$v)
                  {
                  $v = is_array($v) ? implode(',', $v) : $v;
                  }
                 */
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //处理图片
        $row['agency'] = convert_to_oss('card_front_img,card_back_img',$row['agency']);
        //代理地区
        $city_id = $row['city_id'];
        $city_info = (new City())->field('province,city,cityID,name')->where(['cityID'=>$city_id])->find();
        $province_name = (new City())->whereIn('cityID',[$city_info['province'],$city_info['city']])->column('name');
        $province_name = implode('-',$province_name);

        $row['area'] = $province_name.'-'.$city_info['name'];
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}